package com.cssw.fyzb.busi.api.auth;

import com.alibaba.fastjson.JSON;
import com.cssw.fyzb.busi.config.TpsClient;
import com.cssw.fyzb.busi.service.task.TaskService;
import com.cssw.fyzb.busi.service.user.DistrictService;
import com.cssw.fyzb.busi.service.user.UserService;
import com.cssw.fyzb.busi.util.UuidUtil;
import com.cssw.fyzb.core.dao.user.vo.AuthInfoVo;
import com.cssw.fyzb.core.exception.BizException;
import com.cssw.fyzb.core.model.dodb.*;
import com.cssw.fyzb.core.util.BizUtil;
import com.cssw.fyzb.core.util.StringUtil;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import com.ydn.simplecache.SimpleCache;
import com.ydn.simplelock.SimpleLock;
import com.ydn.simplelock.SimpleLockFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigInteger;

/**
 * 人脸核身结果查询
 *
 * @Author zhouxu
 * @create 2020-09-15 22:34
 */
@Function(description = "人脸核身结果查询", parameters = {
        @Parameter(name = "userId", type = Type.String, description = "用户编号", required = true),
        @Parameter(name = "orderNo", type = Type.String, description = "订单号", required = true),
})
@Component
public class TecentFaceAuthQuery implements Action {
    private static final Logger logger = LoggerFactory.getLogger(TecentFaceAuthQuery.class);
    @Autowired
    private UserService userService;
    @Autowired
    private TpsClient tpsClient;
    @Autowired
    private TaskService taskService;
    @Autowired
    private SimpleLockFactory simpleLockFactory;

    @Autowired
    private DistrictService districtService;

    @Autowired
    private SimpleCache simpleCache;

    @Override
    public Response execute(Request request) throws Exception {
        Long userId = request.getLong("userId");
        String orderNo = request.getString("orderNo");

        String nonce = UuidUtil.getNoSpecialChar();
        SimpleLock lock = simpleLockFactory.getLock("USER_" + userId);
        try {
            lock.acquire();
            User user = userService.getById(userId);
            if (user == null) {
                return Response.fail("未找到用户");
            }

            TecentAuthFaceSend authFaceSend = userService.getTecentAuthFaceSend(userId, orderNo);
            if (authFaceSend == null) {
                return Response.fail("请求异常，订单不存在");
            }

            getAuthResult(user, nonce, orderNo, user.getUserName(), user.getIdCard());

            //taskService.collecTask(userId, Long.parseLong(RuleInst.GIVE_TASK), null);
            return Response.success();
        } catch (BizException e) {
            logger.error(e.getErrMsg(), e.getErrCode());
            return Response.fail(e.getErrMsg(), e.getErrCode());
        } catch (Exception e) {
            logger.error("", e);
            return Response.fail(e);
        } finally {
            try {
                lock.release();
            } catch (Exception e) {
                logger.error("", e);
            }
        }

    }

    private void getAuthResult(User user, String nonce, String orderNo, String userName, String idNo) {
        Request request = new Request("TecentFaceAuthQuery");
        request.setParameter("userId", user.getUserId());
        request.setParameter("nonce", nonce);
        request.setParameter("orderNo", orderNo);
        Response response = tpsClient.send(request);
        logger.debug(response.getMessage());
        String msg = response.getOriginalJson();
        if (null != msg && msg.length() > 180) {
            msg = msg.substring(0, 180);
        }
        if (!response.isSuccess()) {
            userService.saveQueryAuthFaceFail(
                    orderNo, nonce, String.valueOf(response.getCode()), msg,
                    user.getUserId(), userName, idNo
            );
            throw new BizException(response.getCode(), response.getMessage());
        }
        userService.saveQueryAuthFaceSucc(
                orderNo, nonce, String.valueOf(response.getCode()), msg,
                user.getUserId(), userName, idNo
        );
        //实名认证信息
//        if (response.getCode() == 0) { //返回code等于0成功 其他失败
        //从缓存中取存入
        String cache = simpleCache.get("AUTHINFOVO" + user.getUserId());
        if (StringUtil.isEmpty(cache)) {
            BizUtil.exception("用户实名信息为空");
        }

        AuthInfoVo vo = JSON.parseObject(cache, AuthInfoVo.class);
        userService.saveAuthInfo(vo.getUserId(), vo.getUserName(), vo.getProvinceCode(), vo.getCityCode(), vo.getDistrictCode(), vo.getIdNo());

        try {
            CmfUser cmf = new CmfUser();
            cmf.setId(new BigInteger(vo.getUserId().toString()));
            // 地区名称
            if (StringUtil.isNotEmpty(vo.getDistrictCode())) {
                District district = districtService.getByCode(vo.getDistrictCode());
                if (district != null) {
                    cmf.setArea(district.getDistrictName());
                }
            }
            // 城市名称
            if (StringUtil.isNotEmpty(vo.getCityCode())) {
                District district = districtService.getByCode(vo.getCityCode());
                if (district != null) {
                    cmf.setCity(district.getDistrictName());
                }
            }
            // 省
            if (StringUtil.isNotEmpty(vo.getProvinceCode())) {
                District district = districtService.getByCode(vo.getProvinceCode());
                if (district != null) {
                    cmf.setProvince(district.getDistrictName());
                }
            }

            userService.updateCmfUser(cmf);

        } catch (Exception e){
            //如果失败也可以继续往下走
            logger.error("", e);
        }

//        } else {
//            userService.saveCmfUserAuth(userName, msg, false, user.getUserId().intValue());
//        }
        //删除缓存
        simpleCache.delete("AUTHINFOVO" + user.getUserId());

        // 修改人脸认证状态
        userService.updateFace(user.getUserId(), User.FACE_YES);

        //如果是已经支付，标记实名成功，并赠送任务
        if (user.isPayAuth()) {
            userService.updateFaceAuth(user, user.FACE_AUTH_YES);
            userService.saveCmfUserAuth(vo.getUserName(), msg, true, user.getUserId().intValue());
            //实名成功，赠送任务
            taskService.collecTask(user.getUserId(), Long.parseLong(RuleInst.GIVE_TASK), null);
        }
    }
}
